package com.mouse.magent.common.util;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpHeaders;

import java.text.MessageFormat;
import java.util.stream.Collectors;

public class HttpUtil {
    public static ByteBuf toBuf(FullHttpRequest request) {
        ByteBuf result = PooledByteBufAllocator.DEFAULT.buffer();
        String resultStr = "{0} {1} {2}\n{3}\n";
        String method = request.method().name();
        HttpHeaders headers = request.headers();
        String endUrl = request.uri().replaceFirst(".*" + headers.get("Host"), "");
        String headerStr = headers.entries().stream().filter(entry -> {
            if ("GET".equalsIgnoreCase(method) && "content-length".equalsIgnoreCase(entry.getKey())) {
                return false;
            }
            return true;
        }).map(entry -> entry.getKey() + ": " + entry.getValue() + "\n").collect(Collectors.joining());
        String msg = MessageFormat.format(resultStr, method, endUrl, request.protocolVersion().text(), headerStr);
        result.writeBytes(msg.getBytes());
        result.writeBytes(request.content());
        return result;
    }
}
